﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mani.Common.Security;
using RastinArgham.CRM.Business;
using Mani.Common;
using System.IO;

namespace RastinArgham.CRM.Web
{
    public class TempStockItem
    {
        public String MAC { get; set; }
        public String SerialNumber { get; set; }
        public String ProductName { get; set; }
        public String MSISDN { get; set; }
        public String Password { get; set; }
        public String DEPTCODE { get; set; }
        public String SUBID { get; set; }
        public String PaymentID { get; set; }
        public int ProductId { get; set; }
    }

    public partial class import_stock_item : System.Web.UI.Page
    {
        public ISecurityManager securityManager { get; set; }
        public CRMRepository crmRepository { get; set; }

        private List<Product> products;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (securityManager == null)
            {
                securityManager = new SecurityManager();
                securityManager.authProvider = new WebAuthorizationProvider();
            }

            if (crmRepository == null)
                crmRepository = new CRMRepository();


            if (!securityManager.IsActionPermitted("import_stock_items")) 
                Response.Redirect("~/access_denied.aspx");

            if (Session["stock_items"] != null)
            {
                LoadStockItems();
            }
        }

        private void LoadStockItems()
        {
            List<TempStockItem> stockItems = (List<TempStockItem>)Session["stock_items"];
            gvStockItems.DataSource = stockItems;
            gvStockItems.DataBind();

            lblCountItems.Text = stockItems.Count + " مورد در فایل یافت شد ";
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (Session["stock_items"] == null)
                return;

            List<TempStockItem> tempStockItems = (List<TempStockItem>)Session["stock_items"];

            foreach (var item in tempStockItems)
            {
                crmRepository.AddStockItem( new StockItem { 
                                                            CreateDate = DateTime.Now, LastUpdate = DateTime.Now, DeptCode = item.DEPTCODE, ImportDate = DateTime.Now, ISDN = item.MSISDN, MAC = item.MAC,
                                                            OperatorId = securityManager.authProvider.GetCurrentUser().UserId, Password = item.Password, PaymentCode = item.PaymentID, ProductId = item.ProductId,
                                                            SerialNumber = item.SerialNumber, Status = (int)StockItemStates.InStock, SubID = item.SUBID
                                          } );
            }

            crmRepository.Save();

            Session["stock_items"] = null;

            UIHelper.ClientAlert(this, "کالاها با موفقیت وارد انبار شدند");
            UIHelper.ClientRedirect(this, "list_stock_items.aspx");
        }

        protected void btnCheckFile_Click(object sender, EventArgs e)
        {
            string message = String.Empty;
            byte[] csvFile = UIHelper.CheckAndGetPostedCSV(fuExcelFile, out message);

            if (csvFile == null && !String.IsNullOrEmpty(message))
            {
                UIHelper.ClientAlert(this, message);
                return;
            }

            Stream s = new MemoryStream(csvFile);
            StreamReader sr = new StreamReader(s);

            string line = sr.ReadLine();
            List<TempStockItem> stockItems = new List<TempStockItem>();

            while (line != null)
            {
                // skipping first line
                line = sr.ReadLine();

                if (line == null)
                    continue;

                string[] values = line.Split(',');

                if (values.Length < 8)
                {
                    sr.Close();
                    s.Close();
                    sr.Dispose();
                    s.Dispose();

                    UIHelper.ClientAlert(this, " فایل اکسل ارسال شده باید حداقل هشت ستون باشد");
                    return;
                }

                TempStockItem t = new TempStockItem { MAC = values[0], SerialNumber = values[1], ProductName = values[2], MSISDN = values[3], Password = values[4], DEPTCODE = values[5], SUBID = values[6], PaymentID = values[7] };

                if (!CheckProductName(t.ProductName))
                {
                    UIHelper.ClientAlert(this, " محصولی با نام " + t.ProductName + " در بانک اطلاعاتی یافت نشد");
                    return;
                }

                t.ProductId = GetProductIdByName(t.ProductName);

                stockItems.Add(t);
            }

            Session["stock_items"] = stockItems;
            UIHelper.ClientAlert(this, "فایل اکسل مورد تایید است با بررسی جدول زیر و اطمینان از درست بودن اطلاعات بر روی ورود به انبار کلیک کنید");
            LoadStockItems();

            sr.Close();
            s.Close();
            sr.Dispose();
            s.Dispose();
        }

        private bool CheckProductName(String ProductName)
        {
            if (products == null)
                products = new List<Product>();

            if (products.Count == 0)
                products = crmRepository.GetProducts();

            var isAvaiable = products.Where(p => p.ProductName.ToLower() == ProductName.ToLower()).FirstOrDefault();

            return (isAvaiable != null);
        }

        private int GetProductIdByName(String ProductName) {
            if (products == null)
                products = new List<Product>();

            if (products.Count == 0)
                products = crmRepository.GetProducts();

            var product = products.Where(p => p.ProductName.ToLower() == ProductName.ToLower()).FirstOrDefault();

            return product.ProductId;
        }

        protected void gvStockItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvStockItems.PageIndex = e.NewPageIndex;
            LoadStockItems();
        }

        protected void gvStockItems_PageIndexChanged(object sender, EventArgs e)
        {
            
        }
    }
}